<?php
require './vendor/autoload.php';
use Anker1992\JWTAuth\Facade\Auth;
use Anker1992\JWTAuth\JWTAuthException;
use Anker1992\JWTAuth\JWTAuthCode;
ini_set('display_errors', 'on');
error_reporting(-1); 

// getToken();
checkToken();
// refreshToken();
// killToken();

//获取令牌
function getToken() {
    $data = [
        'user_id'=>12
    ];
    try{
        $res = Auth::getToken($data);
    }catch (JWTAuthException $e){
        echo json_encode(['error_msg'=>'加密出错']);
    }
    var_dump($res);exit;
}

//权限认证
function checkToken() {
    $token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImtpZCI6ImlhNkhBem14ZkVBdm95MHMifQ.eyJuYmYiOjE2MjE0MTg4ODgsImV4cCI6MTYyMjAyMzY4OCwiand0X2lkZSI6ImlhNkhBem14ZkVBdm95MHMiLCJkYXRhIjp7Im5hbWUiOiJhbmtlciJ9fQ.BuTu-WptVFm1FRYYF8K8g7XGe6-9TPy3FVjTtOqidSI';
    try{
        $res =  Auth::check($token);
    }catch (JWTAuthException $e){
        //token暂时失效，请刷新令牌
        if($e->getCode() === JWTAuthCode::TOKEN_EXPIRE){
            echo json_encode(['error_msg'=> $e->getMessage()]);
        } else if($e->getCode() === JWTAuthCode::INVALID_TOKEN){
            echo json_encode(['error_msg'=>$e->getMessage()]);
        }else{
            echo json_encode(['error_msg'=>'登录过期，请重新登录']);
        }
    }
    var_dump($res);
}

//刷新令牌
function refreshToken() {
    $token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImtpZCI6IjJYUllseU9Sdmg1YkJQd0QifQ.eyJuYmYiOjE2MjE0MTQwNDEsImV4cCI6MTYyMjAxODg0MSwiand0X2lkZSI6IjJYUllseU9Sdmg1YkJQd0QiLCJkYXRhIjp7Im5hbWUiOiJhbmtlciJ9fQ.KcWa839Hb1adfwgHrzbh1m_y4CHf-CQ08iWWlYZXmyY';
    try{
        $res =  Auth::refreshToken($token);
    }catch (JWTAuthException $e){
        echo json_encode(['error_msg'=>'token不合法']);
    }
    var_dump($res);
}

//注销令牌，账号登出
function killToken(){
    $token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImtpZCI6ImlhNkhBem14ZkVBdm95MHMifQ.eyJuYmYiOjE2MjE0MTg4ODgsImV4cCI6MTYyMjAyMzY4OCwiand0X2lkZSI6ImlhNkhBem14ZkVBdm95MHMiLCJkYXRhIjp7Im5hbWUiOiJhbmtlciJ9fQ.BuTu-WptVFm1FRYYF8K8g7XGe6-9TPy3FVjTtOqidSI';
    try{
        Auth::killToken($token);
    }catch (JWTAuthException $e){
        echo json_encode(['error_msg'=>'token不合法']);
    }
    echo('logout success');
}